﻿
//Hàm tách chuỗi CString.
//Giá trị trả về là số chuỗi tách được.
//Ví dụ: 
//		CString mainstr = "anh yeu em";
//		CStringArray cStrArrDovat;
//		int nStrCount = SplitString(mainstr, _T(" "), cStrArrDovat);
//

int SplitString(const CString& xstrInput, const CString& xstrDelimiter, CStringArray& xarrArrayStr) 
{
	// Will return by reference an array of CStrings that are sub strings of 
	// xstrInput. The return of the function is the number of substrings 
	// found. 
	int nPos = 0;
	int nNewPos = -1;
	int nDelimLen = xstrDelimiter.GetLength();
	int nInputLen = xstrInput.GetLength();
	CString str;
	CArray<int, int> arrPositionList;
	xarrArrayStr.RemoveAll();
	nNewPos = xstrInput.Find(xstrDelimiter);
	if(nNewPos >= 0) {
		while(nNewPos > nPos) {
			arrPositionList.Add(nNewPos);
			nPos = nNewPos;
			nNewPos = xstrInput.Find(xstrDelimiter, nPos + nDelimLen);
		}
		int nPosListLen = arrPositionList.GetSize();
		for(int n=0; n <= nPosListLen; n++) {
			if(n == 0) {
				str = xstrInput.Mid(n, arrPositionList[n]);
			} else {
				int nOffset = arrPositionList[n-1] + nDelimLen;
				if (nOffset < nInputLen) {
					if (n == nPosListLen) {
						str = xstrInput.Mid(nOffset);
					} else if (n > 0) {
						str = xstrInput.Mid(arrPositionList[n-1] + nDelimLen,
							arrPositionList[n] - arrPositionList[n-1] - nDelimLen);
					}
				}
			}
			xarrArrayStr.Add(str);
		}
	}
	return xarrArrayStr.GetSize();;
}